﻿using System;
using Modbus.Messages;

namespace Modbus
{
	partial class ModbusClient
	{
		public CommEventLog GetCommEventLog(byte slaveAddress)
		{
			//
			// Input arguments validation.
			//

			Ensure.ArgumentNotEqualTo(SR.Argument_slaveAddress, slaveAddress, BroadcastAddress);

			//
			// Internal state validation.
			//

			this.ThrowIfDisposed();

			//
			// Request creation.
			//

			ModbusMessage request = new ModbusMessage();
			request.FunctionCode = FunctionCodes.GetCommEventLog;

			//
			// Perform transaction.
			//

			var response = this.transport.Request<GetCommEventLogResponse>(slaveAddress, request);

			//
			// Response validation.
			//

			if (response.ByteCount < GetCommEventLogResponse.BytesBeforeEvents)
			{
				// TODO: Throw appropriate exception.
				throw new Exception();
			}

			//
			// Prepare return value.
			//

			CommEventLog log = new CommEventLog(response.Status, response.EventCount, response.MessageCount, response.Events);

			return log;
		}
	}
}
